package com.person.download.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.person.commons.struts2.BaseAction;
import com.person.commons.utils.Constants;
import com.person.commons.utils.FlipPageInfo;
import com.person.download.model.Download;
import com.person.download.service.DownloadService;
import com.person.title.model.TitleFunc;



public class DownloadAction extends BaseAction {
	
	private String downId;
	private String downAlias;
	private String downName;
	private Download download;
	private File fileDown;
	private String fileDownFileName;
	private DownloadService downloadService;
	private FlipPageInfo flipData = new FlipPageInfo();
	private String downHead;
	
	private InputStream inputPath;
	private String contentType;
	private Integer downDown;
	
	
	private String inputPaths;
	private String fileType;
	private String fileName;
	private String uploadName;
	
	
	
	private String annex = "";
	private String annexName = "";
	private TitleFunc titleFunc;

	public InputStream getTargetFile(){
		File file = new File(inputPaths);
		try {
			return new FileInputStream(file);
		} catch (FileNotFoundException e) {
			return ServletActionContext.getServletContext().getResourceAsStream(inputPaths);
		}
	}

	
	/**
	 * 新建下载管理模块的一个上传文件页面
	 * @return
	 */
	public String index(){
		
		return "createDownload";
	}
	/**
	 * 保存下载管理模块上传文件页面上传的东西
	 * @return
	 */
	public String saveDownload(){
		
		
		if(fileDown!=null){
			upload();
		}
		download.setDownDown(0);
		downloadService.saveDownload(download);
		String result = listDownload();
		return result;
	}
	/**
	 * 把下载管理模块里面所上传的文件列表出来
	 * @return
	 */
	public String listDownload(){
		
		flipData = downloadService.findAllDownloadFile(flipData);
		return "listDownload";
	}
	 /**
	  * 删除在服务器上的文件
	  * @param filePathAndName
	  */
	public void delFile(String filePathAndName) { 
		
	     try { 
	       String filePath = filePathAndName; 
	       filePath = filePath.toString(); 
	       File myDelFile = new File(filePath); 
	       myDelFile.delete(); 
	     } 
	     catch (Exception e) { 
	       System.out.println("删除文件操作出错"); 
	       e.printStackTrace(); 
	     } 
	 } 

	/**
	 * 删除下载对象和文件
	 */
	@SuppressWarnings("deprecation")
	public String delete(){
		
		download = downloadService.findDownloadBydownId(downId);
		String filePathAndName=request.getRealPath(File.separator)+
			Constants.DOWNLOAD_DIR+download.getDownAlias();
		delFile(filePathAndName);
		downloadService.deleteDownload(download);
		
		return listDownload();
	}
	/**
	 * 修改下载模块的内容
	 */
	public String modify(){
		
		download = downloadService.findDownloadBydownId(downId);
		titleFunc=downloadService.findTitleFuncByFuncId(download.getFuncId());
		return "editDownload";
	}
	/**
	 * 保存修改后的内容
	 */
	public String saveModify(){
		
		if(fileDown!=null){
			String filePathAndName=request.getRealPath(File.separator)+Constants.DOWNLOAD_DIR+
			download.getDownAlias();
			delFile(filePathAndName);
			upload();
		}
		downloadService.updateDownload(download);
		
		return listDownload();
	}
	/**
	 * 根据条件查询信息列表
	 */
	public String downloadSearch(){
		
		StringBuffer hql = new StringBuffer("select t.funcName,d.downHead,d.downName,d.downSize,d.downDown,d.downId " +
				"from Download d,TitleFunc t where d.funcId=t.funcId ");
		if(!downHead.equals("")&&!downHead.isEmpty()){
			hql.append("and d.downHead like '%"+downHead+"%'");
		}
		if(!downName.equals("")&&!downName.isEmpty()){
			hql.append("and d.downName like '%"+downName+"%'");
		}
		if(!download.getFuncId().isEmpty()&& !download.getFuncId().equals("")){
			hql.append(" and d.funcId ='"+download.getFuncId()+"'");
		}
		hql.append("order by d.funcId,d.downHead asc");
		flipData = downloadService.findDownloadFileByInfo(hql.toString(), flipData);
		
		return "listDownload";	
	}

	/**
	 * 对下载文件的中文名进行编码
	 * @return
	 * @throws UnsupportedEncodingException
	 */

    public String getDownName() throws UnsupportedEncodingException { 
    	   
    	downName=new String(downName.getBytes(),"ISO-8859-1"); 
 
        return downName; 
    }
	/**
	 * 下载文件
	 * @return
	 */

	public String downloadFile(){
		
		download=downloadService.findDownloadBydownId(downId);
		downAlias=download.getDownAlias();
		try{
			inputPath = new FileInputStream(request.getRealPath(File.separator)+
					Constants.DOWNLOAD_DIR+downAlias);
		}catch(FileNotFoundException e){
			e.printStackTrace();
			info="没有找到文件或者文件已经删除";
			return "fileNotFond";
		}
		contentType=downAlias.substring(downAlias.lastIndexOf("."));
		//没下载一次，次数加一
		download.setDownDown(new Integer((download.getDownDown()+1)));
		downName=download.getDownName();
		downloadService.updateDownload(download);
		return SUCCESS;
	}
	/**
	 * 上传文件
	 * @return
	 */
	public String upload(){
		
		String fileType = getFileDownFileName().substring(getFileDownFileName().lastIndexOf("."));
		String fileSourceName = getFileDownFileName().substring(0,getFileDownFileName().lastIndexOf("."));
		String rootDir = request.getRealPath(File.separator)+Constants.DOWNLOAD_DIR;
		String fileTimeName = String.valueOf(new Date().getTime());
		String fileDownDir = rootDir+fileTimeName+fileType;
		
		File rootFile = new File(rootDir);
		File fileDownFile = new File(fileDownDir);
		if (!rootFile.exists()){
			rootFile.mkdirs();
		}
		if(fileDownFile.exists()){
			fileDownFile.delete();
		}
		try{
			FileInputStream in = new FileInputStream(fileDown);
			FileOutputStream out = new FileOutputStream(fileDownDir);
			byte[] buffer = new byte[1024];
			int i = 0;
			if(in!=null){
				while((i = in.read(buffer))> 0){
					out.write(buffer,0,i);
				}
				//获取上传文件大小
				String str=Long.toString(fileDown.length());
				if(str.length()<4){
					str=str+"b";
				}else if(str.length()<7){
					Float temp1=Float.valueOf(str)/1024;
					if(temp1.toString().length()>5){
						str = String.valueOf(temp1).substring(0,5)+"KB";
					}else{
						str = String.valueOf(temp1)+"KB";
					}
				}else if(str.length()<10){
					Float temp2=Float.valueOf(str)/1024/1024;
					str = String.valueOf(temp2).substring(0,5)+"MB";
				}else{
					Float temp3=Float.valueOf(str)/1024/1024/1024;
					str = String.valueOf(temp3).substring(0,5)+"GB";
				}
				download.setDownSize(str);
			}
		}catch(FileNotFoundException e){
			e.printStackTrace();			
		}catch(IOException e){
			e.printStackTrace();
		}
		download.setDownAlias(fileTimeName+fileType);
		download.setDownName(fileSourceName+fileType);
		return fileDownDir;
	}
	/**
	 * @return the download
	 */
	public Download getDownload() {
		return download;
	}
	/**
	 * @param download the download to set
	 */
	public void setDownload(Download download) {
		this.download = download;
	}
	/**
	 * @return the fileDown
	 */
	public File getFileDown() {
		return fileDown;
	}
	/**
	 * @param fileDown the fileDown to set
	 */
	public void setFileDown(File fileDown) {
		this.fileDown = fileDown;
	}
	/**
	 * @return the fileDownFileName
	 */
	public String getFileDownFileName() {
		return fileDownFileName;
	}
	/**
	 * @param fileDownFileName the fileDownFileName to set
	 */
	public void setFileDownFileName(String fileDownFileName) {
		this.fileDownFileName = fileDownFileName;
	}
	/**
	 * @return the downloadService
	 */
	public DownloadService getDownloadService() {
		return downloadService;
	}
	/**
	 * @param downloadService the downloadService to set
	 */
	public void setDownloadService(DownloadService downloadService) {
		this.downloadService = downloadService;
	}
	/**
	 * @return the downAlias
	 */
	public String getDownAlias() {
		return downAlias;
	}
	/**
	 * @param downAlias the downAlias to set
	 */
	public void setDownAlias(String downAlias) {
		this.downAlias = downAlias;
	}
	/**
	 * @param downName the downName to set
	 */
	public void setDownName(String downName) {
		this.downName = downName;
	}
	/**
	 * @return the flipData
	 */
	public FlipPageInfo getFlipData() {
		return flipData;
	}
	/**
	 * @param flipData the flipData to set
	 */
	public void setFlipData(FlipPageInfo flipData) {
		this.flipData = flipData;
	}
	/**
	 * @return the downHead
	 */
	public String getDownHead() {
		return downHead;
	}
	/**
	 * @param downHead the downHead to set
	 */
	public void setDownHead(String downHead) {
		this.downHead = downHead;
	}
	/**
	 * @return the downId
	 */
	public String getDownId() {
		return downId;
	}
	/**
	 * @param downId the downId to set
	 */
	public void setDownId(String downId) {
		this.downId = downId;
	}

	/**
	 * @return the contentType
	 */
	public String getContentType() {
		return contentType;
	}

	/**
	 * @param contentType the contentType to set
	 */
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
	/**
	 * @return the inputPath
	 */
	public InputStream getInputPath() {
		return inputPath;
	}
	/**
	 * @param inputPath the inputPath to set
	 */
	public void setInputPath(InputStream inputPath) {
		this.inputPath = inputPath;
	}
	/**
	 * @return the downDown
	 */
	public Integer getDownDown() {
		return downDown;
	}
	/**
	 * @param downDown the downDown to set
	 */
	public void setDownDown(Integer downDown) {
		this.downDown = downDown;
	}
	/**
	 * @return the titleFunc
	 */
	public TitleFunc getTitleFunc() {
		return titleFunc;
	}
	/**
	 * @param titleFunc the titleFunc to set
	 */
	public void setTitleFunc(TitleFunc titleFunc) {
		this.titleFunc = titleFunc;
	}

	public String getInputPaths() {
		return inputPaths;
	}

	public void setInputPaths(String inputPaths) {
		this.inputPaths = inputPaths;
	}

	public String getFileType() {
		return fileType;
	}

	public void setFileType(String fileType) {
		this.fileType = fileType;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getUploadName() {
		return uploadName;
	}

	public void setUploadName(String uploadName) {
		this.uploadName = uploadName;
	}

	public String getAnnex() {
		return annex;
	}

	public void setAnnex(String annex) {
		this.annex = annex;
	}

	public String getAnnexName() {
		return annexName;
	}

	public void setAnnexName(String annexName) {
		this.annexName = annexName;
	}


	
}
